package com.sbl.bajw.util;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.UUID;

import javax.imageio.ImageIO;

import org.apache.commons.fileupload.FileItem;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class FileUpload {

	public static String saveFile(FileItem item,String targetDir,String fileName) throws Exception
	{		
		String[] fileInfos = item.getName().split("\\.");
		String extension = fileInfos.length>0?"."+fileInfos[fileInfos.length-1]:"";
		
		String newFileName = fileName+extension;
		
		File dir = new File(targetDir);
		
		if(!dir.exists()){
			dir.mkdir();
		}
		
		File file = new File(targetDir,newFileName);
		
		item.write(file);
		return newFileName;
	}
	
	public static String saveImgAndCompression(FileItem item,String targetDir,String buckDir) throws Exception
	{		
		String fileName = item.getName();
		String[] fileInfos = fileName.split("\\.");
		String extension = fileInfos.length>0?"."+fileInfos[fileInfos.length-1]:"";
		
		String newFileName = UUID.randomUUID().toString()+extension;
		File file = File.createTempFile("tem", ".tem");
		
		item.write(file);
		CompressionImg(file,targetDir+newFileName);
		FileUtil.copyFile(targetDir+newFileName, buckDir+newFileName);
		file.delete();

		return newFileName;
	}
	
	public static void CompressionImg(File file,String resultImagePath) throws IOException
	{
	 	ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        BufferedImage bufferedImage = ImageIO.read(file);
        JPEGEncodeParam parm = JPEGCodec.getDefaultJPEGEncodeParam(bufferedImage);
        parm.setQuality(0.05f, false);
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(byteArrayOutputStream, parm);  
        encoder.encode(bufferedImage); 
        
        FileOutputStream resultOut = new FileOutputStream(resultImagePath);
        resultOut.write(byteArrayOutputStream.toByteArray());
        resultOut.flush();
        resultOut.close();
	}

	public static String NewGUID()
	{
		String id = UUID.randomUUID().toString();
		return id;
	}
	
	public static Timestamp GetnNowTimestamp(){
		Timestamp time = new Timestamp(Calendar.getInstance().getTime().getTime());
		return time;
	}
}